<?php
namespace Home\Controller;
use Think\Controller;

/**
 * 订单控制器
 */
class OrderController extends HomeController{
    /**
     * 订单列表
     */
        public function index()
    {
       $order=D('order');
        $result=$order->index();
        //获取支付方式
        $paytype=M('pay_ment')->where('isdisplay=0')->getField('id,name');
        //订单类型
        $areatype=M('config')->where('id=4')->getField('value');
        $areatype=unserialize($areatype);
        //获取订单状态(0未确认，2取消，1确认，3已付款，6配货中，8已发货，9已收货，4退货)
        $allstatus=M('config')->where('id=5')->getField('value');
        $allstatus=unserialize($allstatus);
        $pagearr=$result['pagearr'];
        $orders=$result['orders'];

        $this->assign('allstatus',$allstatus);
        $this->assign('areatype',$areatype);
        $this->assign('paytype',$paytype);
        $this->assign('pagearr',$pagearr);
        $this->assign('orders',$orders);
        $this->display('index');
       

    }


    /*
     * 通过ajax 订单搜索
     * @param 
     * return json
     */
    public function searchOrder()
    {
        $order=D('order');
        $result=$order->index();
        if(!empty($result['orders'])){
            $result['status']=1;
            
            echo json_encode($result,JSON_UNESCAPED_UNICODE);
            return '';

        }

        $result['status']=0;
        $result['message']='暂无数据';
        echo  json_encode($result,JSON_UNESCAPED_UNICODE);
    }



    /**
     * 订单详情
     */
    public function detail(){
        $where['orderid']=$_GET['id'];
        $re=M('order_item')->where($where)->select();
        foreach($re as $k=>$v){
            $res=M('order')->where("orderid='%s'",$v['orderid'])->select();
            foreach ($res as $key => $value) {
                if($v['orderid']==$value['orderid']){
                    $supper=M('supper_user')->where("supperid='%s'",$v['supperid'])->getField("supperid,name,mobile,telephone,address");
                    foreach($supper as $keys=>$r){
                        $re[$k]['name']=$r['name'];
                        $re[$k]['mobile']=$r['mobile'];
                        $re[$k]['telephone']=$r['telephone'];
                        $re[$k]['address']=$r['address'];
                        $re[$k]['order_sn']=$value['order_sn'];
                        $re[$k]['create_time']=$value['create_time'];
                        $re[$k]['order_amount']=$value['order_amount'];
                        $re[$k]['pay_type']=$value['pay_type'];
                        $re[$k]['consignee']=$value['consignee'];
                        $re[$k]['delivery']=$value['delivery'];
                        $re[$k]['logistic_num']=$value['logistic_num'];

                    }
                }
            }
        }

        $map['itemid']=M('order_item')->where($where)->getField("itemid");
        $over=M('item')->where($map)->Field("price,supperprice")->find();
        //获取所有物流公司
        $express_company=M('express_company')->getField('companyid,company,kuaidi');
        
        $profit=$over['price']-$over['supperprice'];///毛利额
        $rate=$profit/$over['price'];///毛利率
        $rate=round($rate,2);
        $rate=$rate*100;
        $this->assign('re',$re);
        $this->assign('rate',$rate);
        $this->assign('profit',$profit);
        $this->assign('express_company',$express_company);
        $this->display();

    }
    /*
     * 导出订单
     * @param  orderids 
     * return csv
     */
    public function putCsv(){
        $string=I('get.orderids','','strip_tags');
        $string=trim($string);
        $orderids=explode(',', $string);
        $where['a.orderid']= !empty($orderids)?array('in',$orderids):'';
        //获取订单基本信息
        $order=M('order a');
        $product=M('product');
        $item=M('item');
        $temp=$order->join('inner join '.C(DB_PREFIX).'order_item b on a.orderid=b.orderid')
                    ->where($where)
                    ->getField('a.orderid,a.order_sn,FROM_UNIXTIME(a.create_time, "%Y-%m-%d %H:%i:%S") as create_time,a.pay_type,b.itemname,b.brand,b.sn,b.specvale,b.number,a.order_amount,b.supperprice,b.price,a.shopid,a.consignee,a.mobile,a.province,a.city,a.district,a.address,b.itemid,b.productid,b.supperid');
        //获取商品库存
        foreach ($temp as $key =>&$value) {
            
            $value['alladdress']=$value['province'].$value['city'].$value['district'].$value['address'];

            if(!empty($value['productid'])){
                $value['inventory']=$product->where('productid=%d',$value['productid'])->getField('inventory');
            }else{
                $value['inventory']=$item->where('itemid=%d',$value['itemid'])->getField('inventory');
            }
            //计算毛利
            $value['grossprofit']=$value['price']-$value['supperprice'];
            $value['grossprofit']=round($value['grossprofit'],2);
            //计算毛利率
            $res=$value['grossprofit']/$value['price'];
            $value['grossmargin']=(round($res*100,2)).'%';
            //获取商家及运营商名称
            $value['shopname']=M('shop_user')->where('shopid=%d',$value['shopid'])->getField('companyname');
            $tp=M()->query('select companyname from '.C(DB_PREFIX).'yunying_user where yid=( select founder from '.C('DB_PREFIX').'shop_user where shopid= '.$value['shopid'].')');
            $value['yunname']=$tp[0]['companyname'];
            $value['pay_type']=!empty($value['pay_type'])?'支付宝支付':'银行转账';
            unset($value['shopid']);
            unset($value['itemid']);
            unset($value['productid']);
            unset($value['supperid']);
            unset($value['province']);
            unset($value['city']);
            unset($value['district']);
            unset($value['address']);
        }
        foreach ($temp as $key => &$value)
         {
            $value['order_sn']=$value['order_sn']."\t";
        }
        
        $csv=A('Home/Csv');
        $csv_title=array('序号','  订单号','  下单时间','支付方式','商品名称','商品品牌','商品型号','颜色','销售数量','销售金额','商品供价','商品售价','收货人','联系方式','收货地址','库存','毛利','毛利率','销售门店','所属运营商');
        $csv->put_csv($temp,$csv_title);
    }
    //ajax 调用订单操作记录
    public function orderAction()
    {
        $result=array();
        $orderid=I('post.orderid',0,'strip_tags');
        $action=D('Order');

        $temp=$action->orderLog($orderid);
        
        if(!empty($temp)) {
            $result['status']=1;
            $result['logs']=array_values($temp);
            echo json_encode($result,JSON_UNESCAPED_UNICODE);
        }else{
            $result['status']=0;
            echo json_encode($result,JSON_UNESCAPED_UNICODE);
        }
    }
    /*
     *ajax fahuo
     *@param logistic_num 物流单号
     *@param delivery   物流公司编号
     *return json
     *    
    */
   public function ajaxDelivery(){
    $result=array();
    $supperid=!empty($_SESSION['supperid'])?$_SESSION['supperid']:0;
    $sname=M('supper_user')->where('supperid=%d',$supperid)->getField('name');
    $orderid=I('post.orderid',0,'strip_tags');
    $logistic_num=I('post.logistic_num',0,'strip_tags'); //物流单号
    $delivery=I('post.delivery','','strip_tags'); 

    if ( empty($orderid) || empty($logistic_num) || empty($delivery) ||empty($sname))
    {
       
        $result['status']=0;
        $result['msg']='参数错误';
        echo  json_encode($result,JSON_UNESCAPED_UNICODE);
        return '';
    }

    //更新orde 订单状态
    $where['orderid']=$orderid;
    $order=M('order');
    $action=M('order_action');
    $order->startTrans();
    $order->create();
    $order->order_status =5;
    $order->pay_status =1;
    $order->shipping_status =2;
    $order->logistic_num =$logistic_num;
    $order->delivery=$delivery;
    $temp1=$order->where($where)->save();

    //添加订单操作表
    $action->create();

    $action->order_id=$orderid;
    $action->action_user=$sname;
    $action->order_status =5;
    $action->pay_status =1;
    $action->shipping_status =2;
    $action->edittime=time();

    $temp2=$action->add();
    if ($temp1 !==false && !empty($temp2))
    {
        $order->commit();// 成功提交
        $result['status']=1;
        $result['msg']='发货成功！';
        echo json_encode($result,JSON_UNESCAPED_UNICODE);
        return '';

    }else{
        $order->rollback();//失败回滚
        $result['status']=0;
        $result['msg']='系统繁忙，请稍后再试';
        echo json_encode($result,JSON_UNESCAPED_UNICODE);
        return '';
    }


   }


    /*
     *查看物流
     */
    public function express()
    {
       
        $typeCom=$_GET["com"];
        $typeNu=$_GET["nu"];

        if(isset($typeCom)&&isset($typeNu))
        {
            $AppKey='8744adc4417e5d8e';
            $url= 'http://www.kuaidi100.com/applyurl?key='.$AppKey.'&com='.$typeCom.'&nu='.$typeNu;
            if(function_exists('curl_init') == 1)
            {
                $curl=curl_init();
                curl_setopt($curl, CURLOPT_URL, $url);
                curl_setopt($curl, CURLOPT_HEADER,0);
                curl_setopt($curl, CURLOPT_RETURNTRANSFER,1);
                curl_setopt($curl,CURLOPT_USERAGENT,$_SERVER['HTTP_USER_AGENT']);
                curl_setopt($curl, CURLOPT_TIMEOUT,5);
                $get_content = curl_exec($curl);curl_close ($curl);
            }
           echo('<iframe src="'.$get_content.'" width="580"height="380"><br/>');
          return '';
        }
        echo false;
        return '';
    }
  






    
}